#!/usr/bin/env python
# coding=utf-8
"简单博客实现"

#载入web.py框架
import web
#载入数据库操作model模块
import model
#载入系统模块
import sys

#url 路由配置
urls = (
    '/', 'Index',
    '/view/(\d+)', 'View',
    '/new', 'New',
    '/delete/(\d+)', 'Delete',
    '/edit/(\d+)', 'Edit',
    '/login', 'Login',
    '/logout', 'Logout',
)
#应用
app = web.application(urls,globals())
#模版公共变量
t_globals = {
    'datestr' : web.datestr,
    'cookie' : web.cookies 
}
#制定模版目录，设定公共模版
#base 是基类模版，类似master page
render = web.template.render('templates', base='base', globals=t_globals)
#创建登录表单
login = web.form.Form(
    web.form.Textbox('username'),
    web.form.Password('password'),
    web.form.Button('login')
)

#首页控制器
class Index:
    def GET(self):
        login_form = login() #空登录表单
        posts = model.get_posts() #读取所有博客
        #渲染index模版
        return render.index(posts, login_form)

    def POST(self):
        login_form = login()
        if login_form.validates():
            f = login_form.d
            if f.username == "admin" and f.password == "admin":
                web.setcookie('username',login_form.d.username)
        raise web.seeother('/')

#查看博客控制器
class View:
    def GET(self, id):
        post = model.get_post(int(id))
        return render.view(post)

#新建博客控制器
class New:
    form = web.form.Form(
        web.form.Textbox('title',
            web.form.notnull,
            size = 30,
            description='Post title:'),
        web.form.Textarea('content',
            web.form.notnull,
            rows = 30,
            cols = 80,
            description='Post content:'),
        web.form.Button(u'发表博客'),
    )
    def GET(self):
        form = self.form()
        return render.new(form)
    def POST(self):
        form = self.form()
        if not form.validates():
            return render.new(form) #输入有问题，重新输入
        model.new_post(form.d.title, form.d.content)
        raise web.seeother('/')

#删除文章类
class Delete:
    def POST(self, id):
        model.del_post(int(id))
        raise web.seeother('/')

#编辑文章类
class Edit:
    def GET(self, id):
        post = model.get_post(int(id))
        form = New.form()
        form.fill(post) # 用读到的博客填充表单
        return render.edit(post,form)
    def POST(self, id):
        form = New.form()
        post = model.get_post(int(id))
        if not form.validates():
            return render.edit(post, form)
        model.update_post(int(id), form.d.title, form.d.content)
        raise web.seeother('/')

#退出登录类
class Logout:
    def GET(self):
        web.setcookie('username','',expires=-1)
        raise web.seeother('/')
#定义404页面
def my404():
    return web.notfound(u"抱歉，你访问的页面不存在.")

app.notfound = my404
#启动web服务
if __name__ == '__main__':
    #设置系统默认编码是utf-8
    reload(sys)
    sys.setdefaultencoding('utf-8')
    #启动web
    app.run()

